// pages/mycard/edit/index.js
//import Dialog from "../../../miniprogram_npm/@vant/weapp/dialog/dialog"
const uploadImage = require("../../../utils/uploadImg/uploadImg.js");
const rules = require('../../../utils/util.js')
const service = require('../../../service/mycard')
import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    alllist: [],
    postfile: "",
    postlogo:"",
    postvedio: "",
    postImage: [],
    fileList: [],
    logolist:[],
    viediofile: [],
    imagelist: [],
    src: "",
    imagesrc:"",
    itemList: [{
      name: "邮箱",
      id: 1
    }, {
      name: "QQ号",
      id: 2
    }, {
      name: "公司网页",
      id: 3
    }, {
      name: "座机号",
      id: 4
    }, {
      name: "取消",
      id: 0
    }],
    itemList1: [{
      name: "英文名",
      id: 5
    }, {
      name: "学历",
      id: 6
    }, {
      name: "取消",
      id: 0
    }],
    show: false,
    show1: false,
    addType: "",
    cardId:"",

    name: "",
    enname: "",
    phone: "",
    qq: "",
    email: "",
    tel: "",
    companyName: "",
    companyYear:"",
    position: "",
    address: "",
    mainBusiness: "",
    education: "",
    registeredCapital: "",
    peopleNum: "",
    legalPerson: "",
    companyWeb:"",

    nameErrorText: "",
    phoneErrorText: "",
    emailErrorText: "",
    telErrorText: "",
    companyErrorText: "",
    positionErrorText: "",
    companyemailErrorText: "",
    yearErrorText:"",
    moneyErrorText: "",
    numErrorText:"",
    showEmail: false,
    showQQ: false,
    showcompanyUrl: false,
    showtel: false,
    showEnname: false,
    showeducation: false,
    btnText: "上传视频"
  },
  afterRead: function (e) {
    // console.log(e);
    var list = this.data.fileList;

    list.push({
      url: e.detail.file.path,
      name: "头像"
    });
    this.setData({
      fileList: list,
      imagesrc: e.detail.file.path,
    });
  },
  afterReadlogo: function (e) {
    // console.log(e);
    var list = this.data.logolist;

    list.push({
      url: e.detail.file.path,
      name: "logo"
    });
    this.setData({
      logolist: list,

    });
  },
  afterReadviedio: function (e) {
    console.log(e);
    var list = this.data.viediofile;
    list[0] = {
      url: e.detail.file.path,
      
      name: "视频"
    };
    this.setData({
      viediofile: list,
      src:e.detail.file.path,
      btnText: "重新上传"
    });
  },
  afterReadimage: function (e) {
    // console.log(e);
    var list = this.data.imagelist;
    list.push({
      url: e.detail.file.path,
      name: "相册"
    });
    this.setData({
      imagelist: list,
    });
  },

  deletephoto: function (event) {
    const {
      index,
      name
    } = event.detail;
    const fileList = this.data.fileList;
    fileList.splice(index, 1);
    this.setData({
      fileList: fileList,
    });
  },
  deletelogo: function (event) {
    const {
      index,
      name
    } = event.detail;
    const fileList = this.data.logolist;
    fileList.splice(index, 1);
    this.setData({
      logolist: fileList,
    });
  },
  deletevedio: function (e) {
    const {
      index,
      name
    } = event.detail;
    const fileList = this.data.viediofile;
    fileList.splice(index, 1);
    this.setData({
      viediofile: fileList,
    });
  },
  deleteimage: function (event) {
    const {
      index,
      name
    } = event.detail;
    const fileList = this.data.imagelist;
    fileList.splice(index, 1);
    this.setData({
      imagelist: fileList,
    });
  },
  blurEvent(e) {

    if (e.detail.value == '') {
      this.setData({
        nameErrorText: '姓名不能为空！',
      });
    } else {
      this.setData({
        nameErrorText: '',
        name: e.detail.value
      });
    }
  },
  blurEventphone(e) {
    if (e.detail.value == '') {
      this.setData({
        phoneErrorText: '电话不能为空！',
      });
    } else {
      this.setData({
        phoneErrorText: '',
        phone: e.detail.value
      });
    }
  },
  blurEventcompany(e) {
    if (e.detail.value == '') {
      this.setData({
        companyErrorText: '公司名称不能为空！',
      });
    } else {
      this.setData({
        companyErrorText: '',
        companyName: e.detail.value
      });
    }
  },
  blurEventposition(e) {
    if (e.detail.value == '') {
      this.setData({
        positionErrorText: '职位不能为空！',
      });
    } else {
      this.setData({
        positionErrorText: '',
        position: e.detail.value
      });
    }
  },
  blurEventenname(e){
    console.log(e)
    if(e.currentTarget.dataset.type=="enname"){
      this.setData({
        enname: e.detail.value
      });
    }else if(e.currentTarget.dataset.type=="education"){
      this.setData({
        education: e.detail.value
      });
    }else if(e.currentTarget.dataset.type=="address"){
      this.setData({
        address: e.detail.value
      });
    }else if(e.currentTarget.dataset.type=="邮箱"){
      this.setData({
        email: e.detail.value
      });
    }else if(e.currentTarget.dataset.type=="QQ"){
      this.setData({
        qq: e.detail.value
      });
    }else if(e.currentTarget.dataset.type=="公司网页"){
      this.setData({
        companyWeb: e.detail.value
      });
    }else if(e.currentTarget.dataset.type=="座机号"){
      this.setData({
        tel: e.detail.value
      });
    }else if(e.currentTarget.dataset.type=="registeredCapital"){
      this.setData({
        registeredCapital: e.detail.value
      });
    }else if(e.currentTarget.dataset.type=="peopleNum"){
      this.setData({
        peopleNum: e.detail.value
      });
    }else if(e.currentTarget.dataset.type=="legalPerson"){
      this.setData({
        legalPerson: e.detail.value
      });
    }else if(e.currentTarget.dataset.type=="mainBusiness"){
      this.setData({
        mainBusiness: e.detail.value
      });
    }else if(e.currentTarget.dataset.type=="companyYear"){
      this.setData({
        companyYear: e.detail.value
      });
    }
    
  },

  onChangephone(e) {
    console.log(e.detail)
    if (!rules.regPhone(e.detail)) {
      this.setData({
        phoneErrorText: '手机号格式有误！',
      });
    } else {
      this.setData({
        phoneErrorText: '',
      });
    }
  },
  onChangeEmail(e) {
    console.log(e.detail)
    if (!rules.isEmail(e.detail)) {
      this.setData({
        emailErrorText: '邮箱格式有误！',
      });
    } else {
      this.setData({
        emailErrorText: '',
      });
    }
  },

  onChangeTel(e) {
    if (!rules.checkTel(e.detail)) {
      this.setData({
        telErrorText: '座机号码格式有误！',
      });
    } else {
      this.setData({
        telErrorText: '',
      });
    }
  },
  onChangeyear(e) {
    if (!rules.checkint(e.detail)) {
      this.setData({
        yearErrorText: '公司成立年数只能为正整数！',
      });
    } else {
      this.setData({
        yearErrorText: '',
      });
    }
  },
  onChangemoney(e) {
    if (!rules.checknumber(e.detail)) {
      this.setData({
        moneyErrorText: '注册资金只能为数字！',
      });
    } else {
      this.setData({
        moneyErrorText: '',
      });
    }
  },
  onChangenum(e) {
    if (!rules.checkint(e.detail)) {
      this.setData({
        numErrorText: '公司人数只能为正整数！',
      });
    } else {
      this.setData({
        numErrorText: '',
      });
    }
  },

  hideitem(e) {
    console.log(e)
    if (e.currentTarget.dataset.type == "邮箱") {
      this.setData({
        showEmail: false,
        email:""
      })
    } else if (e.currentTarget.dataset.type == "QQ") {
      this.setData({
        showQQ: false,
        qq:""
      })
    } else if (e.currentTarget.dataset.type == "公司网页") {
      this.setData({
        showcompanyUrl: false,
        companyWeb:""
      })
    } else if (e.currentTarget.dataset.type == "enname") {
      this.setData({
        showEnname: false,
        enname:""
      })
    } else if (e.currentTarget.dataset.type == "education") {
      this.setData({
        showeducation: false,
        education:""
      })
    } else {
      this.setData({
        showtel: false,
        tel:""
      })
    }
  },

  addMore(e) {
    // console.log(e);
    this.setData({
      show1: true,
      addType: e.currentTarget.dataset.addtype
    })
  },
  addMore1(e) {
    // console.log(e);
    this.setData({
      show: true,
      addType: e.currentTarget.dataset.addtype
    })
  },
  choose(e) {

    if (e.currentTarget.dataset.index == 0) {
      this.setData({
        show: false,
        show1: false,
      })
    } else if (e.currentTarget.dataset.index == 1) {
      this.setData({
        showEmail: true,
        show: false,
      })
    } else if (e.currentTarget.dataset.index == 2) {
      this.setData({
        showQQ: true,
        show: false,
      })
    } else if (e.currentTarget.dataset.index == 3) {
      this.setData({
        showcompanyUrl: true,
        show: false,
      })
    } else if (e.currentTarget.dataset.index == 4) {
      this.setData({
        showtel: true,
        show: false,
      })
    } else if (e.currentTarget.dataset.index == 5) {
      this.setData({
        showEnname: true,
        show1: false,
      })
    } else if (e.currentTarget.dataset.index == 6) {
      this.setData({
        showeducation: true,
        show1: false,
      })
    }
  },
  submit() {
    if (this.data.name == "") {
      this.setData({
        nameErrorText: '姓名不能为空！',
      });

      return
    }
    if (this.data.phone == "") {
      this.setData({
        phoneErrorText: '电话不能为空！',
      });

      return
    }
    if (this.data.company == "") {
      this.setData({
        companyErrorText: '公司名称不能为空！',
      });

      return
    }
    this.data.alllist = Array.prototype.concat.call(this.data.fileList,this.data.logolist, this.data.viediofile, this.data.imagelist);
    console.log(this.data.alllist);

    if (this.data.alllist.length > 0) {
      wx.showLoading({
        title: "正在上传文件",
        mask: true,
      });
      var self = this;
      var album = [];

      function uploadimg() {
        if (self.data.alllist.length > 0) {
          var imgpath = self.data.alllist.pop();
          if(imgpath.cardId){
            album.push({
              "picUrl": imgpath.url,
              // "cardId":imgpath.cardId
            });
            self.setData({
              postImage: album
            })
            uploadimg()
          }else if(imgpath.url.indexOf("hopermall")!=-1&&imgpath.name=="头像"){
            self.setData({
              postfile: imgpath.url
            })
            uploadimg()
          }else if(imgpath.url.indexOf("hopermall")!=-1&&imgpath.name=="视频"){
            self.setData({
              postvedio: imgpath.url
            })
            uploadimg()
          }else if(imgpath.url.indexOf("hopermall")!=-1&&imgpath.name=="logo"){
            self.setData({
              postlogo: imgpath.url
            })
            uploadimg()
          }
          else{
            uploadImage(
              imgpath.url,
              "images/",
              function (result) {
                console.log("======上传成功地址为：", result);
                if (imgpath.name == "头像") {
  
                  self.setData({
                    postfile: result
                  })
  
                } else if (imgpath.name == "视频") {
                  self.setData({
                    postvedio: result
                  })
                } else if (imgpath.name == "logo") {
                  self.setData({
                    postlogo: result
                  })
                } else {
                  album.push({
                    "picUrl": result,
                    // "cardId":self.data.cardId
                  });
                  self.setData({
                    postImage: album
                  })
  
                }
  
                //这个result就是返给你上传到oss上的地址链接
                uploadimg();
              },
              function (result) {
                console.log("======上传失败======", result);
                Toast.fail("上传失败");
                // wx.hideLoading();
                uploadimg();
              }
            );
          }
         
        } else {
          self.addcard();

        }
      }
      uploadimg();

    } else {
      this.addcard()
    }

  },
  addcard() {
    console.log(this.data.postfile, this.data.postvedio, this.data.postImage)
    service.updatecard({
      "cardId": this.data.cardId,
      "headPic": this.data.postfile,
      //名字
      "name": this.data.name,
      //职位
      "position": this.data.position,
      //公司名称
      "companyName": this.data.companyName,
      //英文名
      "enname": this.data.enname,
      //学历
      "education": this.data.education,
      //公司地址
      "address": this.data.address,
      //电话
      "phone": this.data.phone,
      //邮箱
      "email": this.data.email,
      //qq
      "qq": this.data.qq,
      //公司邮箱
      "companyEmail": "",
      //座机
      "tel": this.data.tel,
      //注册资金
      "registeredCapital": this.data.registeredCapital,
      //公司人数
      "peopleNum": this.data.peopleNum,
      //公司成立年数
      "companyYear": this.data.companyYear,
      //主营业务
      "mainBusiness": this.data.mainBusiness,
      //发定代表人
      "legalPerson": this.data.legalPerson,
      //视频地址
      "video": this.data.postvedio,
      //客户标识
      "customerId": wx.getStorageSync('userInfo').id,
      "companyWeb":this.data.companyWeb,
      "companyLogo":this.data.postlogo,
      "businesscardPicList":this.data.postImage
    }, res => {
      console.log(res)
      wx.hideLoading();
      if (res.code == "B0001"||res.code == "500") {
        Toast.fail(res.message);
        return
      }
      
      Toast.success("修改成功");
      wx.navigateBack()
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //debugger;
    //console.log(options)
    wx.showLoading({
      title: "加载中...",
    });
    service.getCardDetail(options.cardId, res => {
      console.log(res)
      wx.hideLoading();
      if (res.data.headPic != "") {
        var list = this.data.fileList;
        list.push({
          url: res.data.headPic,
          
          name: "头像"
        });
        this.setData({
          fileList: list,
          imagesrc:res.data.headPic
        });
      };
      if (res.data.companyLogo != ""&&res.data.companyLogo != null) {
        var list = this.data.logolist;
        list.push({
          url: res.data.companyLogo,
          
          name: "logo"
        });
        this.setData({
          logolist: list,
          
        });
      };
      if (res.data.video != "") {
        var list = this.data.viediofile;
        list[0] = {
          url: res.data.video,
          name: "视频"
        };
        this.setData({
          viediofile: list,
          src: res.data.video,
          btnText: "重新上传"
        });
      }; 
      if (res.data.businesscardPicList.length != 0) {
        var list = this.data.imagelist;
        for (let i = 0; i < res.data.businesscardPicList.length; i++) {
          const element = res.data.businesscardPicList[i];         
          list.push({
            url: element.picUrl,
            name: "相册",
            cardId:element.cardId
          });
        }
        this.setData({
          imagelist: list,
        });
      }
      if(res.data.enname!=""){
        this.setData({
          showEnname:true
        })
      }
      if(res.data.education!=""){
        this.setData({
          showeducation:true
        })
      }
      if(res.data.email!=""){
        this.setData({
          showEmail:true
        })
      }
      if(res.data.qq!=""){
        this.setData({
          showQQ:true
        })
      }
      if(res.data.companyWeb!=""){
        this.setData({
          showcompanyUrl:true
        })
      }
      if(res.data.tel!=""){
        this.setData({
          showtel:true
        })
      }
      this.setData({
        cardId:res.data.cardId,
        name: res.data.name,
        enname: res.data.enname,
        phone: res.data.phone,
        qq: res.data.qq,
        email: res.data.email,
        tel: res.data.tel,
        companyName: res.data.companyName,
        companyYear:res.data.companyYear,
        position: res.data.position,
        address: res.data.address,
        mainBusiness: res.data.mainBusiness,
        education: res.data.education,
        registeredCapital: res.data.registeredCapital,
        peopleNum: res.data.peopleNum,
        legalPerson: res.data.legalPerson,
        companyWeb:res.data.companyWeb,
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})